package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.mq.vo.IotMsgNotifyData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * dataService业务层处理
 * 
 * @author alexis
 * @date 2025-11-11
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询data
     * 
     * @param id data主键
     * @return data
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询data列表
     * 
     * @param deviceData data
     * @return data
     */
    @Override
    public TableDataInfo  selectDeviceDataList(DeviceDataPageReqDto dto)
    {
        // 设置分页参数
        Page<DeviceData> page = new Page(dto.getPageNum(), dto.getPageSize());

        LambdaQueryWrapper<DeviceData> wrapper = new LambdaQueryWrapper<>();
        // 构建条件
        if(StringUtils.isNotEmpty(dto.getDeviceName())){
        wrapper.eq(DeviceData::getDeviceName,dto.getDeviceName());
        }
        if(StringUtils.isNotEmpty(dto.getFunctionId())){
            wrapper.eq(DeviceData::getFunctionId,dto.getFunctionId());
        }
        if(ObjectUtil.isNotEmpty(dto.getStartTime()) && ObjectUtil.isNotEmpty(dto.getEndTime())){
            wrapper.between(DeviceData::getAlarmTime,dto.getStartTime(),dto.getEndTime());
        }
        Page<DeviceData> result = page(page, wrapper);
        TableDataInfo  tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setTotal(result.getTotal());
        tableDataInfo.setRows(result.getRecords());
        return  tableDataInfo;
    }

    /**
     * 新增data
     * 
     * @param deviceData data
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改data
     * 
     * @param deviceData data
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除data
     * 
     * @param ids 需要删除的data主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除data信息
     * 
     * @param id data主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void batchSaveDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        // 完成设备数据 批量保存
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId,iotId);
        Device device = deviceMapper.selectOne(wrapper);
        if(device == null){
            return;
        }
        // 获取body数据---->services
        iotMsgNotifyData.getBody().getServices().forEach(s ->{
            Map<String, Object> properties = s.getProperties();
            if(ObjectUtil.isEmpty(properties)){
                return;
            }
            String eventTimeStr = s.getEventTime();
            LocalDateTime eventTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            // 时区转换
          final LocalDateTime  eventTime2=eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            ArrayList<DeviceData> list = new ArrayList<>();
            properties.forEach((key,value)->{
                DeviceData deviceData = DeviceData.builder()
                        .iotId(iotId)
                        .deviceName(device.getDeviceName())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(key)
                        .accessLocation(device.getRemark())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .dataValue(value + "")
                        .alarmTime(eventTime2)
                        .build();
                list.add(deviceData);
            });

            saveBatch(list);
            // redis保存数据
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_DATA_LAST,iotId,
                    JSONUtil.toJsonStr(list));

        });


    }
}
